/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package klient;

import Serializable.ParsedCmd;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.SwingWorker;

/**
 *
 * @author Marcin
 */
public class Sender extends SwingWorker <Void,Void>{

    @Override
    protected Void doInBackground() throws Exception {
        
        Socket s;
        try{
            s= new Socket(Connection.HOST,Connection.SPORT);
            ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
            NonBlockingInput<ParsedCmd> nbi = new NonBlockingInput<>(ois);
            nbi.start();
            
            ParsedCmd inPC;
            ParsedCmd outPC;
            
            boolean waiting=false;
            oos.writeObject(new ParsedCmd("HAI"));
            
            while(true){
                if(waiting){
                    long sTime = System.currentTimeMillis();
                    while(!nbi.ready()){
                        Thread.sleep(10);
                        if(System.currentTimeMillis()-sTime > Klient.timeout)
                            throw new Exception();
                    }
                    waiting = false;
                }
                
                if(nbi.ready()){
                    inPC=nbi.read();
                    Klient.log("Serwer: "+inPC.mainCmd);
                
                    if (inPC.mainCmd.equals("GG"))
                        break;
                    
                    outPC=Protocol.process(inPC, Klient.uS);
                    if(outPC.needAnswer)
                        waiting=true;
                }else{
                    if(Protocol.needAny(Klient.uS)){
                        outPC=Protocol.makeReq(Klient.uS).needAnswer();
                        waiting = true;
                    }else{
                        outPC=Bridge.req(null);
                        if(outPC==null)
                            outPC=new ParsedCmd();
                    }
                }
                
                
                if(!outPC.isEmpty()){
                    Klient.log("Klient: "+outPC.mainCmd);
                    oos.writeObject(outPC);
                }
            }
            
            ois.close();
            oos.close();
            s.close();
        }catch(Exception e){
            e.printStackTrace();
            Klient.log("Serwer niedostępny!");
            Klient.uS.setState(UserState.NO_CONNECTED);
        }
        
        return null;
    }
    
}
